package handlers

import (
	"github.com/gin-gonic/gin"
	"pet-manage-sys/cache"
	"pet-manage-sys/morders"
	"pet-manage-sys/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redis_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}

	var user morders.User

	err := morders.DB.Where("username=?", username).First(&user).Error

	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名或密码错误",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	cache.Rdb.Incr(cache.Ctx, redis_key)

	cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误,封禁2个小时",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登陆成功",
		"data": user,
	})
	return

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")

	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := morders.Dog{
		Title:   title,
		Content: content,
	}

	err := morders.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var dog []morders.Dog
	err := morders.DB.Offset(offset).Limit(size).Find(&dog).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
	})
	return

}
